package com.ruoyi.purchase.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.*;
import com.ruoyi.company.service.*;
import com.ruoyi.company.utils.Util;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/business/purchase")
public class PurchaseOrderController extends BaseController {

    private String prefix = "purchase";
    @Autowired
    ExpressDeliveryService expressDeliveryService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    private ICompanyInvoiceService invoiceService;

    @Autowired
    private AuditService auditService;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    ICompanyLinkmanServer iCompanyLinkmanServer;

    @Autowired
    ICompanyMyLinkmanServer iCompanyMyLinkmanServer;

    @Autowired
    ProcurementServer procurementServer;

    @RequiresPermissions("business:purchase:view")
    @GetMapping()
    public String order() {
        return prefix + "/list";
    }

    /**
     * 查询采购订单列表
     */
    @RequiresPermissions("business:purchase:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime,
                              @RequestParam(value = "deptName", required = false) String deptName,
                              @RequestParam(value = "purchaseStatus", required = false) String purchaseStatus) {

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setBeginTime(beginTime);
        purchaseOrder.setEndTime(endTime);
        purchaseOrder.setDeptName(deptName);
        purchaseOrder.setPurchaseStatus(purchaseStatus);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        startPage();
        Long companyId = sysUser.getCompanyId();
        if (!sysUser.getDeptId().equals(companyId)) {
            purchaseOrder.setUserId(sysUser.getUserId());
        }
        List<PurchaseOrder> list = purchaseOrderService.selectPurchaseOrderList(purchaseOrder);
        return getDataTable(list);
    }

    @PostMapping("/insert")
    @ResponseBody
    public void insert(ExpressDelivery expressDelivery) {

        String creatime = getTime();
        expressDelivery.setCreatetime(creatime);
        String loginname = ShiroUtils.getLoginName();
        expressDelivery.setLoginname(loginname);
        try {
            expressDeliveryService.insert(expressDelivery);

        } catch (Exception e) {

        }
    }

    @PostMapping("/selectProductType")
    @ResponseBody
    public List<Integer> selectProductType(HttpServletRequest request) {
        String productType = request.getParameter("productType");
        return procurementServer.selectProductType(productType);
    }



    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "purchaseId", required = false) Long purchaseId,
                                @RequestParam(value = "purchaseStatus", required = false) String purchaseStatus) {
        PurchaseOrder purchaseOrder=new PurchaseOrder();
        purchaseOrder.setPurchaseId(purchaseId);
        purchaseOrder.setPurchaseStatus(purchaseStatus);
        return toAjax(purchaseOrderService.auditSale(purchaseOrder));
    }


    /**
     * 根据销售订单生成采购合同ajax
     */
    @PostMapping("/dataIntoContract")
    @ResponseBody
    public JSONObject dataIntoContract(Long purchaseId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("purchaseId", purchaseId);
        hashMap.put("deptId", sysUser.getCompanyId());
        PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderByMap(hashMap);
        //供方 信息;
        Company purchaseData = iCompanyServer.selectByCompanyId(purchaseOrder.getSupplierId());
        CompanyInvoice purchaseInvoiceData = iCompanyInvoiceService.selectByCompanyId(purchaseOrder.getSupplierId());

        Map<String, Object> linkMap = new HashMap<>();
        linkMap.put("deptId", sysUser.getCompanyId());
        linkMap.put("companyId", purchaseOrder.getSupplierId());
        List<CompanyLinkman> companyLinkmen = iCompanyLinkmanServer.selectLinkman(linkMap);
        CompanyLinkman companyLinkman = companyLinkmen.get(0);

        //需方 信息;
        Company demanderData = iCompanyServer.selectByCompanyId(purchaseOrder.getDeptId());
        CompanyInvoice demanderInvoiceData = iCompanyInvoiceService.selectByCompanyId(purchaseOrder.getDeptId());

        Map<String, Object> myLinkMap = new HashMap<>();
        myLinkMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<CompanyMyLinkman> companyMyLinkmen = iCompanyMyLinkmanServer.selectLinkman(linkMap);
        CompanyMyLinkman companyMyLinkman = new CompanyMyLinkman();
        if (companyMyLinkmen.size() != 0) {
            companyMyLinkman = companyMyLinkmen.get(0);
        }

        JSONObject jsonObject = new JSONObject();
        //合同编号 是销售订单的编号
        jsonObject.put("contractNo", purchaseOrder.getPurchaseNum());
        //供方
        jsonObject.put("purchaseName", iSysDeptService.selectDeptById(purchaseOrder.getSupplierId()).getDeptName());
        //签订日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(purchaseOrder.getPurchaseDate()));
        //需方
        jsonObject.put("demander", iSysDeptService.selectDeptById(purchaseOrder.getDeptId()).getDeptName());
        //签订地点
        Map map = new HashMap();
        map.put("deptId", purchaseOrder.getDeptId());
        map.put("companyId", purchaseOrder.getSupplierId());
        map.put("gradeStatus", "02");

        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        jsonObject.put("contractAddress", purchaseData.getCity());
        //采购订单产品
        JSONArray jsonArrayModel = new JSONArray();
        if (purchaseOrder.getPurchaseModel() != null) {
            for (int i = 0; i < purchaseOrder.getPurchaseModel().size(); i++) {
                jsonArrayModel.add(purchaseOrder.getPurchaseModel().get(i));
            }
            jsonObject.put("models", jsonArrayModel);
        }
        if (purchaseOrder.getPurchaseModel() != null) {
            //总数量
            int totalNum = 0;
            for (int i = 0; i < purchaseOrder.getPurchaseModel().size(); i++) {
                totalNum += purchaseOrder.getPurchaseModel().get(i).getPurchaseNum();
            }
            jsonObject.put("totalNum", totalNum);
        }

        //总金额
        jsonObject.put("totalMoney", purchaseOrder.getTaxAmount());
        //合计人民币
        BigDecimal taxamount = purchaseOrder.getTaxAmount();
        double saleorderTaxamount = taxamount.doubleValue();
        jsonObject.put("upperMoney", upperCase(saleorderTaxamount));

        //合同约定项
        JSONArray jsonContractTerms = new JSONArray();
        String contractTerms = companyOther.getContractTerms();
        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        if (!"".equals(contractTerms) && contractTerms != null) {
            contractTermsArr = contractTerms.split("\\r?\\n");
        }
        for (int i = 0; i < contractTermsArr.length; i++) {
            String str = contractTermsArr[i];
            jsonContractTerms.add(str);
        }
        jsonObject.put("contractTerms", jsonContractTerms);

        //供货单位
        //地址
        jsonObject.put("purchaseAddress", purchaseData.getProvince() + purchaseData.getCity() + purchaseData.getOtherCorporateAddress());

        //印章
        String purSeal = "";
        if (purchaseData.getElectronicSealUrl() != null && !"".equals(purchaseData.getElectronicSealUrl())) {
            purSeal = purchaseData.getElectronicSealUrl();
            purSeal = purSeal.split("/profile/upload")[1];
            try {
                purSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + purSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //            if (purchaseData.getSealUrl() != null && !"".equals(purchaseData.getSealUrl())) {
//                purSeal = purchaseData.getSealUrl();
//                try {
//                    purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company2 = new Company();
////                company2.setSealUrl("/seal/" + imgname);
////                company2.setCompanyId(purchaseData.getCompanyId());
////                purSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company2);
//            }
////            try {
////                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }
        if (!purSeal.equals("")) {
            jsonObject.put("purSeal", "data:image/jpg;base64," + purSeal);
        }

        //电话
//        jsonObject.put("purchasePhone", purchaseInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("purchasePhone", companyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("purchaseSocialCreditCode", purchaseData.getSocialCreditCode());
        //开户
        jsonObject.put("purchaseBank", purchaseInvoiceData.getDepositBank());
        //账号
        jsonObject.put("purchaseBankNum", purchaseInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("purchaseCustomerForStaff", purchaseData.getCorporateRepresentative());
        jsonObject.put("purchaseCustomerForStaff", companyLinkman.getName());
        //供货单位
        //地址
        jsonObject.put("demanderAddress", demanderData.getProvince() + demanderData.getCity() + demanderData.getOtherCorporateAddress());

        //印章
        String demanderSeal = "";
        if (demanderData.getElectronicSealUrl() != null && !"".equals(demanderData.getElectronicSealUrl())) {
            demanderSeal = demanderData.getElectronicSealUrl();
            demanderSeal = demanderSeal.split("/profile/upload")[1];

            try {
                demanderSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + demanderSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            if (demanderData.getSealUrl() != null && !"".equals(demanderData.getSealUrl())) {
//                demanderSeal = demanderData.getSealUrl();
//                try {
//                    demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
//                    String downloadPath = RuoYiConfig.getDownloadPath();
//                    File file = new File(downloadPath);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company3 = new Company();
////                company3.setSealUrl("/seal/" + imgname);
////                company3.setCompanyId(demanderData.getCompanyId());
////                demanderSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company3);
//            }
////            try {
////                demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }
        if (!demanderSeal.equals("")) {
            jsonObject.put("demanderSeal", "data:image/jpg;base64," + demanderSeal);
        }

        //邮编

        //电话
//        jsonObject.put("demanderPhone", demanderInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("demanderPhone", companyMyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("demanderSocialCreditCode", demanderData.getSocialCreditCode());

        //开户
        jsonObject.put("demanderBank", demanderInvoiceData.getDepositBank());
        //账号
        jsonObject.put("demanderBankNum", demanderInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("demanderCustomerForStaff", demanderData.getCorporateRepresentative());
        jsonObject.put("demanderCustomerForStaff", companyMyLinkman.getName());

        return jsonObject;
    }

    /**
     * 新增采购订单时需要的数据
     */
    @GetMapping("/selectInformation")
    public Map<String, Object> add() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> resMap = new HashMap<>();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dates = a.parse(a.format(new Date()));
            resMap.put("purchaseNum", orderNum(dates, 0));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long companyId = sysUser.getCompanyId();
        Long deptId = sysUser.getDeptId();
        Long userId = sysUser.getUserId();

        Map<String, Object> map = new HashMap();
        map.put("deptId", companyId);
        if (!sysUser.getDeptId().equals(companyId)) {
            map.put("userId", sysUser.getUserId());

        }
        //供应商
        resMap.put("supplier", userService.selectSupplierByMap(map));
//        mmap.put("supplier", userService.selectSupplierById(companyId));
//        mmap.put("user", userService.selectSalesmanList(companyId));

        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }

        Company companyInvoice = iCompanyServer.selectByCompanyId(companyId);
        //用户

        resMap.put("user", sysUsers);
        resMap.put("users", i);
        resMap.put("taxRate", companyInvoice.getTaxRate());
        return resMap;
    }

    /**
     * 生成采购订单编号
     */
    @PostMapping("/orderNum")
    @ResponseBody
    public String orderNum(Date date, Integer i) {
        i=1;
        return purchaseOrderService.orderNum(date, i);
    }


    /**
     * 新增保存采购订单
     */
    @RequiresPermissions("business:purchase:add")
    @Log(title = "新增保存采购订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody PurchaseOrder purchaseOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (purchaseOrder.getPurchaseModel() == null) {
            return AjaxResult.error("请选择需要采购的产品");
        }
        String purchaseNum = purchaseOrder.getPurchaseNum();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("purchaseNum", purchaseNum);
        map1.put("deptId", sysUser.getCompanyId());
        PurchaseOrder purchaseOrder1 = purchaseOrderService.selectPurchaseOrderByMap(map1);
        if (purchaseOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
//              dates = a.parse(a.format(new Date()));
                dates = a.parse(a.format(purchaseOrder.getPurchaseDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = orderNum(dates, 0);
            purchaseOrder.setPurchaseNum(s);
        }
        return toAjax(purchaseOrderService.insertPurchaseOrder(purchaseOrder));
    }

    /**
     * 点击修改采购订单查询所需的数据
     */
    @GetMapping("/selectEdit/{purchaseId}")
    public Map<String, Object> selectEdit(@PathVariable(value = "purchaseId", required = false) Long purchaseId) {

        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
        List<PurchaseModel> purchaseModels = purchaseOrderService.selectPurchaseModelById(purchaseId);
        Long companyId = sysUser.getCompanyId();
        Long userId = sysUser.getUserId();
        Company companyInvoice = iCompanyServer.selectByCompanyId(companyId);
        Long deptId = sysUser.getDeptId();
        Map<String, Object> map = new HashMap();
        map.put("deptId", companyId);
        if (!sysUser.getDeptId().equals(companyId)) {
            map.put("userId", sysUser.getUserId());
        }
        resMap.put("supplier", userService.selectSupplierByMap(map));
//        mmap.put("supplier", userService.selectSupplierById(ShiroUtils.getSysUser().getCompanyId()));
        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }
        //用户
        resMap.put("user", sysUsers);
        resMap.put("users", i);
//        mmap.put("user", userService.selectSalesmanList(companyId));

        resMap.put("purchaseOrder", purchaseOrder);

        resMap.put("purchaseModels", purchaseModels);

        resMap.put("taxRate", companyInvoice.getTaxRate());
        JSONArray jsonArray = selectProduct(purchaseOrder.getSupplierId());
        resMap.put("jsonArray", jsonArray);

        // 获取上一条临近的ID
        resMap.put("previousId", purchaseOrderService.querypreviousId(purchaseId));
        // 获取下一条临近的ID
        resMap.put("nextId", purchaseOrderService.queryNextId(purchaseId));
        return resMap;
    }

    /**
     * 查看采购订单
     */
    @GetMapping("/look/{purchaseId}")
    public String look(@PathVariable("purchaseId") Long purchaseId, ModelMap mmap) {
        PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
        List<PurchaseModel> purchaseModels = purchaseOrderService.selectPurchaseModelById(purchaseId);
        mmap.put("supplier", userService.selectSupplierById(ShiroUtils.getSysUser().getCompanyId()));
        mmap.put("user", userService.selectSalesmanList(ShiroUtils.getSysUser().getCompanyId()));
        mmap.put("purchaseOrder", purchaseOrder);
        mmap.put("purchaseModels", purchaseModels);
        mmap.put("taxRate", invoiceService.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId()));
        JSONArray jsonArray = selectProduct(purchaseOrder.getSupplierId());
        mmap.put("jsonArray", jsonArray);
        return prefix + "/look";
    }

    /**
     * 修改保存保存采购订单
     */
    @RequiresPermissions("business:purchase:edit")
    @Log(title = "修改保存采购订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody PurchaseOrder purchaseOrder) {
        if (purchaseOrder.getPurchaseModel() == null) {
            return AjaxResult.error("请选择需要采购的产品");
        }
        return toAjax(purchaseOrderService.updatePurchaseOrder(purchaseOrder));
    }

    /**
     * 复制采购订单
     */
    @RequiresPermissions("business:purchase:add")
    @Log(title = "复制采购订单", businessType = BusinessType.DELETE)
    @PostMapping("/copy")
    @ResponseBody
    public AjaxResult copy(@RequestParam("purchaseId") Long purchaseId) {
        return toAjax(purchaseOrderService.copyPurchaseOrderById(purchaseId));
    }

    /**
     * 查询供应商的绑定业务员
     */
    @GetMapping("/selectUser/{companyId}")
    @ResponseBody
    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }
//    @PostMapping("/selectUser")
//    @ResponseBody
//    public AjaxResult selectUser(@RequestParam("companyId") Long companyId) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("deptId", ShiroUtils.getSysUser().getCompanyId());
//        map.put("companyId", companyId);
//        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
//        if (companyOther != null) {
//            return AjaxResult.success(companyOther);
//        } else {
//            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
//        }
//    }

    /**
     * 删除采购订单
     */
    @RequiresPermissions("business:purchase:remove")
    @Log(title = "删除采购订单", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{purchaseId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("purchaseId") Long purchaseId) {
        return toAjax(purchaseOrderService.deletePurchaseOrderById(purchaseId));
    }

    /**
     * 查询供应商下的所有产品
     */
    @Log(title = "查询供应商下的所有产品", businessType = BusinessType.DELETE)
    @PostMapping("/selectProduct/{deptId}")
    @ResponseBody
    public JSONArray selectProduct(@PathVariable("deptId") Long deptId) {

        List<Product> productList = purchaseOrderService.selectProduct(deptId);
        JSONArray array = new JSONArray();
        for (Product product : productList) {
            if (product.getProductModel().size() != 0) {
                List<ProductModel> productModels = product.getProductModel();
                for (ProductModel productModel : productModels) {
                    JSONObject obj = new JSONObject();
                    obj.put("productId", product.getProductId());
                    obj.put("productName", product.getProductName());
                    obj.put("modelNo", productModel.getModelNo());
                    obj.put("modelCode", productModel.getModelCode());
                    obj.put("productType", productModel.getProductType());
                    obj.put("salesUnit", productModel.getSalesUnit());
                    array.add(obj);
                }
            } else {
                JSONObject obj = new JSONObject();
                obj.put("productId", product.getProductId());
                obj.put("productName", product.getProductName());
                array.add(obj);
            }
        }

        return array;
    }

    /**
     * 查询项目--跳转页面
     */
    @GetMapping("selectProductModelList/{supplierId}")
    public String selectProductModelList(@PathVariable("supplierId") Long supplierId, ModelMap mmap) {
        mmap.put("supplierId", supplierId);
        return prefix + "/selectProductModelLists";
    }

    /**
     * 查询所有产品型号规格
     *
     * @param product 查询条件
     * @return
     */
    @RequiresPermissions("business:purchase:list")
    @GetMapping("/selectProductModelLists")
    public TableDataInfo selectProductModelLists(@RequestParam(value = "deptId", required = false) Long deptId,
                                                 @RequestParam(value = "productName", required = false) String productName,
                                                 @RequestParam(value = "productType", required = false) String productType) {

        Product product = new Product();
        product.setDeptId(deptId);
        product.setProductName(productName);
        product.setProductType(productType);
        startPage();
        return getDataTable(purchaseOrderService.selectProductLists(product));
    }

    /**
     * /**
     * 重写分页数据
     *
     * @param msg  提示信息
     * @param list 数据
     * @return 结果
     */
    protected TableDataInfo getDataTable2(String msg, List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }

    /**
     * 根据 ModelCode查询 最新订单的价格
     */
    @PostMapping("/selectNewPrice")
    @ResponseBody
    public String selectNewPrice(Long productId, String modelCode) {

        HashMap hashMap = new HashMap();
        hashMap.put("productId", productId);
        hashMap.put("modelCode", modelCode);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<BigDecimal> price = purchaseOrderService.selectSaleorderNewPrice(hashMap);
        if (price.size() != 0) {
            BigDecimal bigDecimal = price.get(0);
            return bigDecimal.toString();
        } else {
            return "";
        }
    }

    /**
     * 下拉表格
     */
    @GetMapping("/selectTableRow")
    public JSONObject tableSelect(@RequestParam(value = "supplierId", required = false) Long supplierId, @RequestParam(value = "productType", required = false) String productType) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        Map map = new HashMap<String, Object>();
        if (supplierId != null & !"".equals(supplierId)) {
            map.put("deptId", supplierId);
            map.put("productType", productType);
            map.put("allowSharing", 0);
        }
        List<Product> products = purchaseOrderService.selectProducts(map);
        JSONArray array = new JSONArray();
        for (Product product : products) {
            if (product.getProductModel().size() != 0) {
                List<ProductModel> productModels = product.getProductModel();
                for (ProductModel productModel : productModels) {
                    JSONObject obj = new JSONObject();
                    obj.put("productId", product.getProductId());
                    obj.put("productName", product.getProductName());
                    obj.put("modelNo", productModel.getModelNo());
                    obj.put("modelCode", productModel.getModelCode());
                    obj.put("productType", productModel.getProductType());
                    obj.put("warehousingNum", productModel.getWarehousingNum());
                    obj.put("unit", productModel.getUnit());
                    obj.put("factor", productModel.getFactor());
                    array.add(obj);
                }
            }
        }
        jsonObject.put("data", array);
        return jsonObject;
    }

    /**
     * 查询产品下所有的规格型号
     */
    @Log(title = "查询产品下所有的规格型号", businessType = BusinessType.DELETE)
    @PostMapping("/selectProductModel/{productId}")
    @ResponseBody
    public JSONArray selectProductModel(@PathVariable("productId") Long productId, ModelMap mmap) {
        List<ProductModel> productModelList = purchaseOrderService.selectProductModel(productId);
        JSONArray array = new JSONArray();
        for (ProductModel productModel : productModelList) {
            JSONObject obj = new JSONObject();
            obj.put("modelNo", productModel.getModelNo());
            obj.put("modelCode", productModel.getModelCode());
            obj.put("productType", productModel.getProductType());
            obj.put("salesUnit", productModel.getSalesUnit());
            array.add(obj);
        }
        return array;
    }

    /**
     * 根据company 查询 公司税率
     */
    @PostMapping("/selectTaxRateById")
    @ResponseBody
    public String selectTaxRateById(@RequestParam("companyId") Long companyId) {
        CompanyInvoice companyInvoice = invoiceService.selectByCompanyId(companyId);
        String taxRate = companyInvoice.getTaxRate() + "%";
        return taxRate;
    }

    /**
     * 根据company 查询 订单审核时间
     */
    @PostMapping("/selectAuditById")
    @ResponseBody
    public Date selectAuditById(@RequestParam("purchaseId") Long purchaseId) {
        Audit audit = new Audit();
        audit.setOrderId(purchaseId);
        audit.setOrderType("1");
        audit = auditService.selectAuditByOrderId(audit);
        return audit.getAuditTime();
    }

    /**
     * 将金额转换为 大写
     *
     * @param money
     * @return
     */
    private String upperCase(double money) {
        String[] upNum = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String[] danwei = {"圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
        //取消科学记数法
        NumberFormat numFormat = NumberFormat.getInstance();
        numFormat.setMaximumFractionDigits(2);//设置小数位个数
        numFormat.setGroupingUsed(false);//取消科学技术发
        String formatNum = numFormat.format(money);
        String strmoney = formatNum + "";//浮点型转为字符型
        String lastUpNum = "null"; //用于存放上个参数的值
        String result = "";//返回的结果
        String[] split = strmoney.split("\\.");
        String strMoney = split[0];
        String point = "";
        //小数部分取值处理。
        if (split.length > 1) {
            point = split[1];
            if (point.length() == 1) {
                point = point.concat("0");
            }
        } else {
            point = "0";
        }
        //大于12位就直接返回。
        int moneyLen = strMoney.length();
        if (money == 0) {
            return "零圆整";
        }
        if (moneyLen > 12) {
            return "金额：" + money + "元，超出大写转换范围。最大金额：999999999999.99元";
        }
        //整数(integer)部分处理。
        if (!"0".equals(strMoney)) {
            for (int i = 0; i < moneyLen; i++) {
                String strNum = strMoney.charAt(i) + "";
                int singleNum = Integer.parseInt(strNum);
                String upSingleNum = upNum[singleNum];
                //上一为不等于0的情况
                if (!"零".equals(lastUpNum)) {
                    if (!"零".equals(upSingleNum)) {
                        result = result.concat(upSingleNum).concat(danwei[moneyLen - i - 1]);
                    } else
                        //为零但是在万、亿位上要加单位 (moneyLen-i)==9 指的是单位：亿。  (moneyLen-i)==5指的是单位：万
                        if ((moneyLen - i) == 5 || (moneyLen - i) == 9) {
                            lastUpNum = "";
                        } else {
                            result = result.concat(upSingleNum);
                        }
                }
                //上一位为0的情况
                if ("零".equals(lastUpNum) && !"零".equals(upSingleNum)) {
                    result = result.concat(upSingleNum).concat(danwei[moneyLen - i - 1]);
                }
                //捕捉上一位数（lastUpNum）为零的情况做优化。
                if ((moneyLen - i) == 5 || (moneyLen - i) == 9) {
                    //排除加单位时前面为"零"的情况。如：两百零万
                    if ("零".equals(lastUpNum) || "null".equals(lastUpNum)) {
                        result = result.substring(0, result.length() - 1);
                    }
                    if (!result.endsWith("亿")) {
                        result = result.concat(danwei[moneyLen - i - 1]);
                    }
                    lastUpNum = "";
                } else {
                    //把当前大写数字复制给 lastUpNum 用于下次判断
                    lastUpNum = upSingleNum;
                }
            }
            //对几万元整和几亿元整(result:五万零或者五亿零零)做优化。
            result = result.replaceAll("零零", "零");
            if (result.endsWith("零")) {
                String substring = result.substring(0, result.length() - 1);
                result = substring;
            }
            result = result.concat("圆");
            result = result.replaceAll("圆圆", "圆");
            result = result.replaceAll("万万", "万");

        }

        //小数(point)部分处理
        if ("0".equals(point)) {
            result = result + "整";
        } else {
            //去 整
//            if(result.endsWith("整")){
//                result = result.substring(0,result.length()-1);
//            }
            if ((point.charAt(0) + "").equals("0")) {
                result = result.concat(upNum[Integer.parseInt(point.charAt(1) + "")] + "分");
            } else if ((point.charAt(1) + "").equals("0")) {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0) + "")] + "角");
            } else {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0) + "")] + "角").concat(upNum[Integer.parseInt(point.charAt(1) + "")] + "分");
            }
        }
        return result;
    }


    @PostMapping("/selectPdfUrlByPurchaseId")
    @ResponseBody
    public JSONArray selectPdfUrlByPurchaseId(Long purchaseId) {
        PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(purchaseOrder.getPdfUrl());
        jsonArray.add(purchaseOrder.getPurchaseNum());
        return jsonArray;
    }

    @GetMapping("/downPdf")
    public void down(String saleorderNum, String pdfUrl, HttpServletRequest request, HttpServletResponse response) {
        String pdfPath = RuoYiConfig.getDownloadPath() + pdfUrl;
        File file = new File(pdfPath);
        OutputStream os = null;
        try {
            FileInputStream in = new FileInputStream(file);
            BufferedInputStream bf = new BufferedInputStream(in);
            os = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=" + saleorderNum + ".pdf");
            byte[] b = new byte[bf.available() + 1000];
            int i;
            while ((i = bf.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
        } catch (IOException ignored) {

        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        System.out.println(dateFormat.format(date));
    }


    public String getTime() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String time = dateFormat.format(date);
        return time;
    }


}